//
//  ClubPushDynamicView.swift
//  77Club
//
//  Created by Apple on 2024/8/28.
//

import UIKit

class ClubDynamicFunctionView: UIView {

    // 按钮的宽度和高度
    private let buttonWidth: CGFloat = 61.0.Scale
    private let buttonHeight: CGFloat = 26.0.Scale
    // 按钮之间的间距
    private let spacing: CGFloat = 12.0.Scale
    
    var functionButtonBlock: ((_ funcID: Int) -> Void)?
    
    var imgStr: [String] = [String]() {
        didSet{
            setupButton()
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)

        backgroundColor = .clear
    }
    
    private func setupButton(){
        
        // for循环创建按钮
        for i in 0..<imgStr.count {
            // 创建按钮
            let button = UIButton(type: .system)
            // 设置按钮的标题
            let image = imgStr[i].toImage?.withRenderingMode(.alwaysOriginal)
            button.setImage(image, for: .normal)
            // 设置按钮的框架（位置和大小）
            let xPosition = CGFloat(i) * (buttonWidth + spacing)
            button.frame = CGRect(x: xPosition, y: 4, width: buttonWidth, height: buttonHeight)
            // 为按钮添加点击事件
            button.addTarget(self, action: #selector(buttonTapped(_:)), for: .touchUpInside)
            button.tag = i
            // 添加按钮到视图中
            self.addSubview(button)
        }
    }
    
    @objc func buttonTapped(_ sender: UIButton) {
        // 按钮点击事件的处理
        functionButtonBlock?(sender.tag)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

//MARK: 搜索view
class ClubDynamicSearchView: UIView, UITableViewDelegate, UITableViewDataSource, RaeNetworkProtocol {

    private lazy var tableView: UITableView = {
        let tableView = UITableView()
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = .clear
        tableView.showsVerticalScrollIndicator = false
        tableView.register(ClubDynamicGameCell.self,ClubDynamicPostCell.self)
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.separatorStyle = .none
        tableView.rowHeight = 45.0.Scale
        return tableView
    }()
    private let bgView = c_make_ex(UIView.self).end()
    private let grayView = c_make_ex(UIView.self)
        .bgColor("#EDEEF0").corner(8.0.Scale).end()
    private let searchView = ClubDynamicSearchTextfieldView()
    
    private var dataModel: [ClubDynamicGameModel]?
    
    private var keyword = ""
    
    //1.话题 2.游戏 3.帖子
    var searchType = 1 {
        didSet{
            loadData()
        }
    }
    var isShowSearchView: (() -> Void)?
    var searchBlock: ((_ model: ClubDynamicGameModel) -> Void)?
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)

        backgroundColor = .clear

        subviews{
            bgView
            grayView.subviews{
                searchView
                tableView
            }
        }
        
        bgView.fillContainer()
        bgView.isUserInteractionEnabled = true
        let emptyTap = UITapGestureRecognizer(target: self, action: #selector(clickEmptyView))
        bgView.addGestureRecognizer(emptyTap)
        grayView.top(0).leading(56.0.Scale).trailing(12.0.Scale).height(300.0.Scale)
        searchView.top(0).leading(0).trailing(0).height(45.0.Scale)
        tableView.leading(0).trailing(0).height(255.0.Scale)
        tableView.Top == searchView.Bottom
        
        searchView.searchBlock = { word in
            self.keyword = word
            self.loadData()
        }
        
    }
    
    private func loadData(){
        
        dataModel?.removeAll()
//        ToastUtil.show()
        if searchType == 1 {
            Task {
                let models = await network.requestSpecialData(.dynamicTopic(keyword: keyword),type: ClubDynamicGameModel.self)
//                ToastUtil.dismiss()
                if models.isSuccess, let models = models.models {
                    var tempModels = [ClubDynamicGameModel]()
                    for var md in models {
                        md.type = "1"
                        tempModels.append(md)
                    }
                    self.dataModel = tempModels
                    self.tableView.reloadData()
                }
            }
        }else if searchType == 2 {
            Task {
                let models = await network.requestSpecialData(.dynamicGame(keyword: keyword),type: ClubDynamicGameModel.self)
//                ToastUtil.dismiss()
                if models.isSuccess, let models = models.models {
                    var tempModels = [ClubDynamicGameModel]()
                    for var md in models {
                        md.type = "2"
                        tempModels.append(md)
                    }
                    self.dataModel = tempModels
                    self.tableView.reloadData()
                }
            }
        }else if searchType == 3 {
            Task {
                let models = await network.requestSpecialData(.searchPost(keyword: keyword),type: ClubDynamicGameModel.self)
//                ToastUtil.dismiss()
                if models.isSuccess, let models = models.models {
                    var tempModels = [ClubDynamicGameModel]()
                    for var md in models {
                        md.type = "3"
                        tempModels.append(md)
                    }
                    self.dataModel = tempModels
                    self.tableView.reloadData()
                }
            }
        }
    }
    
    @objc private func clickEmptyView(){
        self.keyword = ""
        self.searchView.searchTextF.text = ""
        isShowSearchView?()
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return dataModel?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if searchType == 3 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "ClubDynamicPostCell", for: indexPath) as! ClubDynamicPostCell
            cell.model = dataModel?[indexPath.row]
            return cell
        }
        let cell = tableView.dequeueReusableCell(withIdentifier: "ClubDynamicGameCell", for: indexPath) as! ClubDynamicGameCell
        cell.model = dataModel?[indexPath.row]
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        if let md = dataModel?[indexPath.row] {
            searchBlock?(md)
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}


class ClubDynamicSearchTextfieldView: UIView {
    
    let searchTextF = c_make_ex(UITextField.self)
        .border("#323233", width: 1).corner(15.0.Scale)
        .placeholder("请输入关键进行搜索").color("#323233").end()
    private let clearButton = c_make_ex(UIButton.self)
        .image("Dynamic_push_clear").end()
    
    var searchBlock: ((_ words: String) -> Void)?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        backgroundColor = .clear
        
        subviews{
            searchTextF
            clearButton
        }
        
        searchTextF.leading(16.0.Scale).trailing(16.0.Scale).top(12.0.Scale).height(30.0.Scale)
        clearButton.size(18.0.Scale).trailing(71.0.Scale)
        clearButton.CenterY == searchTextF.CenterY
        
        clearButton.isHidden = true
        searchTextF.style { v in
            let searchB = UIButton(frame: CGRect(x: 3.0.Scale, y: 3.0.Scale, width: 48.0.Scale, height: 24.0.Scale))
            searchB.backgroundColor = "#323233".toColor
            searchB.setTitle("搜索", for: .normal)
            searchB.setTitleColor(.white, for: .normal)
            searchB.titleLabel?.font = 12.font_semiBold
            searchB.layer.cornerRadius = 12.0.Scale
            searchB.layer.masksToBounds = true
            let searchV = UIView(frame: CGRect(x: 0, y: 0, width: 54.0.Scale, height: 30.0.Scale))
            searchV.addSubview(searchB)
            v.rightView = searchV
            v.rightViewMode = .always
            let emptyV = UIView(frame: CGRect(x: 0, y: 0, width: 12.0.Scale, height: 24.0.Scale))
            v.leftView = emptyV
            v.leftViewMode = .always
            v.placehold("#7D7E80".toColor, font: 12.font_medium)
            v.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)
        }
        
        clearButton.addTarget(self, action: #selector(clickClearButton), for: .touchUpInside)
    }
    
    @objc func textFieldDidChange(_ textField: UITextField) {
        
        if textField.text?.count ?? 0 > 0 {
            clearButton.isHidden = false
        }else{
            clearButton.isHidden = true
        }
        
        searchBlock?(textField.text ?? "")
    }
    
    @objc private func clickClearButton(){
        searchTextF.text = ""
        searchBlock?("")
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}


//MARK: 话题或者游戏cell
class ClubDynamicGameCell: UITableViewCell {
    
    private let tabImageV = c_make_ex(UIImageView.self)
        .mode(.scaleAspectFill).end()
    private let titleLabel = c_make_ex(UILabel.self)
        .color("#2E3033").font(12.font_medium).end()
    private let subLabel = c_make_ex(UILabel.self)
        .color("#959699").font(10.font_medium).end()

    var model:ClubDynamicGameModel? {
        didSet{
            guard let md = model else { return }
            
            titleLabel.text = md.name
            if md.type == "1" {
                tabImageV.image = "Dynamic_smallTopic".toImage
                subLabel.text = md.views
            }else if md.type == "2" {
                tabImageV.image = "Dynamic_smallGame".toImage
                subLabel.text = md.number
            }
        }
    }
    
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        selectionStyle = .none
        backgroundColor = .clear
        contentView.backgroundColor = .clear
        
        contentView.subviews{
            tabImageV
            titleLabel
            subLabel
        }
        
        tabImageV.leading(16.0.Scale).top(8.0.Scale).size(12.0.Scale)
        titleLabel.trailing(16.0.Scale).leading(32.0.Scale).top(6.0.Scale)
        subLabel.trailing(16.0.Scale).leading(32.0.Scale)
        subLabel.Top == titleLabel.Bottom + 4.0.Scale
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

//MARK: 帖子cell
class ClubDynamicPostCell: UITableViewCell {
    
    private let logoImgV = c_make_ex(UIImageView.self)
        .mode(.scaleAspectFill).image("Forum_push_postIcon").end()
    private let nameLabel = c_make_ex(UILabel.self)
        .color("#323233").font(10.font_regular).end()
    private let contentLabel = c_make_ex(UILabel.self)
        .color("#333333").font(12.font_medium).end()

    var model:ClubDynamicGameModel? {
        didSet{
            guard let md = model else { return }
            
            nameLabel.text = md.fabu
            contentLabel.text = md.title
        }
    }
    
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        selectionStyle = .none
        backgroundColor = .clear
        contentView.backgroundColor = .clear
        
        contentView.subviews{
            logoImgV
            nameLabel
            contentLabel
        }
        
        logoImgV.leading(16.0.Scale).top(8.0.Scale).size(12.0.Scale)
        nameLabel.trailing(16.0.Scale).leading(32.0.Scale)
        nameLabel.CenterY == logoImgV.CenterY
        contentLabel.trailing(16.0.Scale).leading(32.0.Scale)
        contentLabel.Top == logoImgV.Bottom + 4.0.Scale
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
